package com.ccteam.fluidmusic.ui.setting

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ccteam.fluidmusic.utils.Event
import com.ccteam.fluidmusic.view.bean.ErrorMessage
import com.ccteam.fluidmusic.view.bean.LoadMessage
import com.ccteam.model.Resource
import com.ccteam.shared.core.UserCore
import com.ccteam.shared.domain.auth.LogoutDataUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/4/5
 *
 * 设置界面相关ViewModel
 */
@HiltViewModel
class SettingViewModel @Inject constructor(
    private val userCore: UserCore,
    private val logoutDataUseCase: LogoutDataUseCase
): ViewModel() {

    /**
     * 设置相关加载状态信息
     * 如登出时的错误提醒
     */
    private val _loadMessage = MutableLiveData<Event<LoadMessage>>()
    val loadMessage: LiveData<Event<LoadMessage>> get() = _loadMessage

    /**
     * 是否应展示账户相关按钮
     */
    private val _shouldShowAccount = MutableLiveData<Boolean>()
    val shouldShowAccount: LiveData<Boolean> get() = _shouldShowAccount

    init {
        viewModelScope.launch {
            userCore.isLogin.collectLatest {
                _shouldShowAccount.value = it
            }
        }
    }

    /**
     * 退出登录
     */
    fun logout(){
        viewModelScope.launch {
            val result = logoutDataUseCase(null)
            if(result is Resource.Success){
                _loadMessage.value = Event(LoadMessage.Success)
            } else {
                _loadMessage.value = Event(LoadMessage.Error(ErrorMessage(result.message,result.errorCode)))
            }
        }
    }
}